package servlet.dept;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import dao.DepartmentDao;
import dbutil.DBHelper;
import entity.DeptLicense;
import net.sf.json.JSONObject;

public class AddDeptLicenseServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1591915623244364886L;

	public AddDeptLicenseServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String deptName = request.getParameter("deptName");
		deptName = URLDecoder.decode(URLDecoder.decode(StringUtils.isEmpty(deptName) ? "" : deptName, "UTF-8"), "UTF-8");
		String softName = request.getParameter("softName");
		int licenseNum = Integer.parseInt(request.getParameter("licenseNum"));
		
		JSONObject jsonObject = new JSONObject();
		Connection conn = null;
		DepartmentDao departmentDao = null;
		DeptLicense deptLicense = null;
		List<DeptLicense> list = null;
		
		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			departmentDao = new DepartmentDao();
			deptLicense = new DeptLicense();
			
			deptLicense.setDeptName(deptName);
			deptLicense.setSoftName(softName);
			deptLicense.setLicenseNum(licenseNum);
			deptLicense.setAssigned(0);
			deptLicense.setActivated(0);
			
			list = departmentDao.queryDeptLicense(deptName, softName);
			if(list != null && list.size() > 0) {
				jsonObject.put("retCode", "0");
				jsonObject.put("desc", "已存在此部门分配记录");
			} else {
				if(departmentDao.addDeptLicense(deptLicense)) {
					jsonObject.put("retCode", "1");
					conn.commit();
				} else {
					jsonObject.put("retCode", "0");
					jsonObject.put("desc", "AddDeptLicenseServlet Dao");
					conn.rollback();
				}
			}
			
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "AddDeptLicenseServlet Exception");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}
		
	}

	public void init() throws ServletException {
	}

}
